<template>
    <div>
        <div class="search">
          <input v-model="keywords" type="text" placeholder="输入城市名或拼音">
        </div>
      <div class="search-city" v-show="keywords" ref="searchBox">
         <ul>
           <li class="search-list"
               v-for="item in list"
               :key="item.id"
               @click="handCityClick(item.name)"
           >{{item.name}}</li>
           <li class="search-list" v-show="hasNoData">没有找到匹配数据</li>
         </ul>
      </div>
    </div>
</template>

<script>
    import Bscroll from 'better-scroll'
    export default {
        name: "Search",
        props:{
             cities:Object//接收数据
        },
        data (){
          return{
              keywords:'',//input里的关键字
              list:[],//空数组里储存数据
              timer:null//定时器
          }
        },
        computed:{//计算属性
            hasNoData(){
              return !this.list.length
            }
        },
        methods:{
          handCityClick(city){
            this.$store.dispatch("changeCity",city)
            this.$router.push('/')
          }
        },
        watch:{
            keywords(){
               if(this.timer){
                 clearTimeout(this.timer)
               }
               if(!this.keywords){
                 this.list = [];
                 return
               }
               this.timer=setTimeout(()=>{
                   const result = [];
                   for(let i in this.cities){//遍历对象cities
                      this.cities[i].forEach((value)=>{
                         if(value.spell.indexOf(this.keywords)>=0 || value.name.indexOf(this.keywords)>=0){
                            result.push(value)
                         }
                      })
                   }
                   this.list = result
               },100)
            }
        },
        mounted(){//生命周期函数钩子
            this.scroll = new Bscroll(this.$refs.searchBox)
        }
    }
</script>

<style scoped lang="stylus">
    .search{
      height :.36rem;
      padding :0 .1rem;
      background :#00bcd4;
        input{
          width :100%;
          text-align :center;
          box-sizing :border-box;
          height :.31rem;
          line-height :.31rem;
          border-radius :.06rem;
          padding :0 .1rem;
        }
    }
    .search-city{
        width :100%;
        background :#eeeeee;
        position: absolute;
        top:.76rem;
        left :0;
        bottom :0;
        z-index :1;
        overflow :hidden;
        color :#666;
        .search-list{
           line-height :.28rem;
           border-bottom :1px solid #cccccc;
           padding-left :.1rem;
        }
    }
</style>
